﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ex = Microsoft.Office.Interop.Excel;
using System.Data;
using System.Windows.Forms;

namespace Test
{
    class Excel
    {
        public void ExportToExcel(DataTable dt)
        {
            Ex.Application excel = new Ex.Application();
            Ex.Workbook workbook = excel.Application.Workbooks.Add(true);
            int iCol = 0;
            foreach (DataColumn c in dt.Columns)
            {
                iCol++;
                excel.Cells[1, iCol] = c.ColumnName;
            }
            int iRow = 0;
            foreach (DataRow r in dt.Rows)
            {
                iRow++;
                iCol = 0;
                foreach(DataColumn c in dt.Columns)
                {
                    iCol++;
                    excel.Cells[iRow + 1, iCol] = r[c.ColumnName];
                }
            }
            object missing = System.Reflection.Missing.Value;
            SaveFileDialog sdlg = new SaveFileDialog();
            sdlg.Filter = "xls file|*.xls";
            sdlg.ShowDialog();
            workbook.SaveAs(sdlg.FileName,Ex.XlFileFormat.xlXMLSpreadsheet,missing,missing,false,false,Ex.XlSaveAsAccessMode.xlNoChange, missing, missing, missing, missing, missing);
            excel.Visible = true;
            //Ex.Worksheets workSheet = (Ex.Worksheets)excel.ActiveSheet;
           // ((Ex._Worksheet) workSheet).Activate();
            //((Ex._Application)excel).Quit();
        }
    }
}
